//
//  UserAccountViewModel.swift
//  Swiftsweibo
//
//  Created by 张鹏飞 on 16/1/8.
//  Copyright © 2016年 张鹏飞. All rights reserved.
//

import Foundation

class UserAccountViewModel {
    
    /// 用户账户视图模型单例
    static let sharedUserAccount = UserAccountViewModel()
    
    //用户模型
    var account: UserAccount?
    
 /// 返回有效的 token
    var accessToken: String? {
    
        if !isExpired {
        
            return account?.access_token
        }
        return nil
    }
    /// 用户登录标记
    var userLogon: Bool {
    
        return account?.access_token != nil && !isExpired
    }
    
    /// 用户头像 URL
    var avatar: NSURL {
    
        return NSURL(string: account?.avatar_large ?? "")!
    }
    
    /// 归档保存的路径 - 计算性属性
    private var accountPath: String {
    
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    /// 判断是否过期 (计算型属性)
    private var isExpired: Bool {
        
        //自己改写过期日期判断逻辑是否正确
//        account?.expiresDate = NSDate(timeIntervalSinceNow: -3600)
    
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
        
            return false
        }
        //如果过期返回 true
        return true
    }
    
    init(){
    
        //从沙盒恢复数据,恢复当前数据
       account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        
        if isExpired {
        
            print("已经过期")
            account == nil
        }
    }
}

// MARK: - 用户相关网络方法
extension UserAccountViewModel {

    // 4.加载 AcrossToken
    
    func loadAccessToken(code: String, finished: (isSuccessed: Bool)->()){
    
    NetWorkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
    
    if error != nil {
    
    //失败回调
        finished(isSuccessed: false)
    return
    }
    
        self.account = UserAccount(dict: result as! [String: AnyObject])
    
        self.loadUserInfo(self.account!, finished: finished)
    }
    
//    return false
}


private func loadUserInfo(account: UserAccount, finished: (isSuccessed: Bool)->()) {
    
    NetWorkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
        if error != nil {
            
            print("加载用户信息出错")
            
            finished(isSuccessed: false)
            return
        }
        
        guard let dict = result as? [String : AnyObject] else {
            
            print("格式出错")
            
            finished(isSuccessed: false)
            return
        }
        
        //保存用户信息
        account.screen_name = dict["screen_name"] as? String
        account.avatar_large = dict["avatar_large"] as? String
        
        //保存对象
        NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
        
        finished(isSuccessed: true)
       }
   }
}